package com.dailywork.basepro.xml;

import com.dailywork.basepro.xml.model.Book;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author think
 * @version 2019/10/20
 * @since JDOM解析xml文件
 */
public class ReadXMLByJDom {

    private List<Book> books = null;

    public List<Book> getBooks(String fileName) {
        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            Document document = saxBuilder.build(new FileInputStream(fileName));
            // 获取根节点bookstore
            Element rootElement = document.getRootElement();
            // 获取根节点的子节点，返回子节点的数组
            List<Element> bookList = rootElement.getChildren();
            books = new ArrayList<>();
            for (Element bookElement : bookList) {
                Book book = new Book();
                // 获取bookElement的属性
                List<Attribute> bookAttributes = bookElement.getAttributes();
                for (Attribute attribute : bookAttributes) {
                    if ("id".equals(attribute.getName())) {
                        String id = attribute.getValue();
                        book.setId(Integer.parseInt(id));
                    }
                }
                // 获取bookElement的子节点
                List<Element> children = bookElement.getChildren();
                for (Element child : children) {
                    if ("name".equals(child.getName())) {
                        String name = child.getValue();
                        book.setName(name);
                    } else if ("author".equals(child.getName())) {
                        String author = child.getValue();
                        book.setAuthor(author);
                    } else if ("year".equals(child.getName())) {
                        String year = child.getValue();
                        book.setYear(Integer.parseInt(year));
                    } else if ("price".equals(child.getName())) {
                        String price = child.getValue();
                        book.setPrice(Double.parseDouble(price));
                    }
                }
                books.add(book);
                book = null;
            }

        } catch (IOException | JDOMException e) {
            e.printStackTrace();
        }
        return books;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String fileName = "src/res/books.xml";
        List<Book> books = new ReadXMLByJDom().getBooks(fileName);
        for (Book book : books) {
            System.out.println(book);
        }
    }
}
